#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>



// 实现udp服务端 接收数据

void receive_data(int sockfd) {
    int n = 0;
    char buf[1024] = {0};

    struct sockaddr_in  client_addr;

    socklen_t len = sizeof(client_addr);
    while(1) {
        memset(buf, 0, sizeof(buf));
        n = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &len);
        printf("receive From ip : %s\n", inet_ntoa(client_addr.sin_addr));
        printf("receive from port: %d\n", ntohs(client_addr.sin_port));
        printf("receive data: %s\n", buf);
        if (strncmp(buf, "exit", 4) == 0) {
            break;
        }
    }
    return;
}


int main(int argc, char const *argv[])
{

    struct sockaddr_in my_addr;
    socklen_t len = sizeof(my_addr);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    memset(&my_addr, 0, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(atoi(argv[2]));
    my_addr.sin_addr.s_addr = inet_addr(argv[1]);

    
    // 绑定端口和ip
    if(bind(sockfd, (struct sockaddr *)&my_addr, len) <0) {
        perror("bind error");
        return -1;
    }
    receive_data(sockfd);
    close(sockfd);
    return 0;
}
